<script setup>
import { getLegalAdvice, getDeepSeekResponse } from '@/api/ai'
import BaseIcon from '@/components/Icon/BaseIcon.vue'
import { ref, reactive,onMounted } from "vue";

const inputMesg = ref('');
const isLoading = ref(false);

const messages = reactive([
    {
      sender: 'system',
      text: '您好，我是一个法律咨询机器人，请输入您的问题。',
      timestamp: new Date(),
    }

]);
const formatAiResponse = (text) => {
  if (!text) return ''

  // 1. 自动换行：在句号、问号、感叹号后加换行符
  let formatted = text
      .replace(/([。？！.?])(?=\S)/g, '$1<br/>') // 中英文标点后换行
      .replace(/(《.*?》第\d+条)/g, '<strong>$1</strong>') // 高亮法律条文引用

  // 2. 分段：根据换行符分割成多个段落 <p>
  const paragraphs = formatted.split(/<br\s*\/?>/i).filter(p => p.trim())
  formatted = paragraphs.map(p => `<p>${p.trim()}</p>`).join('\n')

  // 3. 处理列表：识别“第一、”、“1.”等开头的条目并转为<ul><li>
  const listRegex = /((\d+、|\d+\.)\s+.*?)(?=(\d+、|\d+\.)|$)/gs
  formatted = formatted.replace(listRegex, (match) => {
    const items = match.split(/(?=\d+、|\d+\.)/)
    const listItems = items
        .filter(Boolean)
        .map(item => {
          const [prefix, ...rest] = item.split(/^(\d+、|\d+\.)\s*/)
          return `<li>${prefix}<span>${rest.join(' ').trim()}</span></li>`
        })
        .join('\n')
    return `<ul>${listItems}</ul>`
  })

  return formatted
}



const sendMsg = ()=> {
  messages.push({
    sender: 'user',
    text: inputMesg.value,
    timestamp: new Date(),
  })
  isLoading.value = true;
  inputMesg.value = '';


//准备消息历史（只保留最近的4条）
  const recentHistory = messages.slice(-4)
      .filter(msg => msg.sender !== 'system')
      .map(msg => ({
        role: msg.sender === 'user' ? 'user' : 'assistant',
        content: msg.text
      }));

  getLegalAdvice(inputMesg.value, recentHistory).then(res=>{
    const formattedRes = formatAiResponse(res);
    messages.push({
      sender: 'system',
      text: formattedRes,
      timestamp: new Date(),
    })
    isLoading.value = false;
  })
}

</script>


<template>
  <div class="chat-container">
    <div class="msg-container">
      <div class="msg-item" v-for="msg in messages" :key="msg.timestamp">
        <div class="msg-ai" v-if="msg.sender === 'system'">
          <BaseIcon name="kefu1" class="icon-ai"/>
          <div class="msg-content">
<!--            <span>{{ msg.text }}</span>-->
            <div class="msg-html" v-html="msg.text"></div>
          </div>
        </div>
        <div class="msg-self" v-else>
          <div class="msg-content">
            <span>{{ msg.text }}</span>
          </div>
          <BaseIcon name="yonghu" class="icon-self"/>
        </div>
      </div>
      <div class="msg-item" v-if="isLoading">
        <div class="msg-ai">
          <BaseIcon name="kefu1" class="icon-ai"/>
          <div class="msg-content">
            <span>正在思考...</span>
          </div>
        </div>
      </div>
    </div>

    <div class="send-container">
      <input class="send-input" placeholder="输入消息..." v-model="inputMesg"/>
      <button class="send-btn" @click="sendMsg">发送</button>
    </div>
  </div>
</template>

<style scoped>
.msg-html p {
  margin: 0 0 12px 0;
}

.msg-html ul {
  padding-left: 20px;
  margin: 8px 0;
}

.msg-html li {
  margin-bottom: 6px;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #f8f9fa;
  padding: 16px;
  box-sizing: border-box;
}

.msg-container {
  width: 100%;
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 8px;
  gap: 12px;
  box-sizing: border-box;
}

.msg-item {
  width: 100%;
  display: flex;
}

.msg-ai {
  display: flex;
  align-items: flex-start;
  width: 100%;
}

.msg-self {
  display: flex;
  align-items: flex-start;
  width: 100%;
  justify-content: flex-end;
}

.msg-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-break: break-word;
  line-height: 1.4;
  position: relative;
}

.msg-ai .msg-content {
  background-color: #e3f2fd;
  border-top-left-radius: 4px;
  margin-left: 10px;
}

.msg-self .msg-content {
  background-color: #dcedc8;
  border-top-right-radius: 4px;
  margin-right: 10px;
}

.icon-ai {
  position: relative;
  left: 0;
  width: 40px;
  height: 40px;
  color: #2196f3;
  background-color: white;
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.icon-self {
  position: relative;
  right: 0;
  width: 40px;
  height: 40px;
  color: #4caf50;
  background-color: white;
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.send-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 8px 16px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.send-input {
  width: calc(100% - 80px);
  height: 40px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
  padding: 0 16px;
  background-color: #f5f5f5;
  color: #333;
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-input:focus {
  background-color: #ffffff;
  border-color: #4caf50;
}

.send-btn {
  width: 70px;
  height: 40px;
  border: none;
  border-radius: 20px;
  background-color: #4caf50;
  color: #fff;
  cursor: pointer;
  outline: none;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-left: 10px;
}

.send-btn:hover {
  background-color: #3e8e41;
  transform: translateY(-1px);
}

.send-btn:active {
  transform: translateY(0);
}

@media (max-width: 768px) {
  .chat-container {
    padding: 8px;
  }

  .msg-container {
    height: calc(100% - 56px);
    padding: 4px;
    gap: 8px;
  }

  .msg-content {
    max-width: 75%;
    padding: 10px 14px;
  }

  .icon-ai,
  .icon-self {
    width: 36px;
    height: 36px;
  }

  .send-container {
    height: 56px;
    padding: 8px;
  }

  .send-input {
    height: 36px;
    padding: 0 12px;
  }

  .send-btn {
    width: 60px;
    height: 36px;
  }
}
</style>

